<template>
  <el-card>
    <el-form :inline="true">
      <el-form-item label="配置名:">
        <el-select
          v-model="configName"
          placeholder="请选择配置"
          style="width: 240px"
          @change="onSubmitOption"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>

  <div class="config">
    <el-descriptions direction="vertical" title="配置设置" border>
      <el-descriptions-item
        v-for="(item, key) in fields"
        :key="key"
        :label="item.label"
        min-width="400"
      >
        <template v-if="editField === key">
          <div id="edit-input">
            <el-input
              v-model="editingValues[key]"
              @blur="handleBlur(key)"
              @keyup.enter="handleBlur(key)"
              :placeholder="`请输入${item.label}`"
              ref="editableInput"
              @focus="handleFocus"
              @mousedown.stop
              :type="item.types"
              autosize
              clearable
              show-word-limit
            />
          </div>
        </template>
        <template v-else>
          <div>
            <template v-if="item.types === 'switch'">
              <el-switch
                v-model="item.value"
                inline-prompt
                active-text="开启"
                inactive-text="关闭"
                @click="handleSwitchClick(key, item.value)"
              />
            </template>
            <template v-else-if="item.types === 'select'">
              <el-select
                v-model="item.value"
                :placeholder="`请选择${item.label}`"
                style="width: 240px"
                @change="handleSelectChange(key, item.value)"
              >
                <el-option
                  v-for="subitem in item.options"
                  :key="subitem.value"
                  :label="subitem.label"
                  :value="subitem.value"
                />
              </el-select>
            </template>
            <template v-else>
              <div v-show="editField !== key" @click="handleEdit(key)">
                {{ item.value }}
              </div>
            </template>
          </div>
        </template>
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template>
    
    <script setup>
import { reactive, ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import { getOption, getConfig, updateConfig } from "../api/scriptsetup";
import { ElMessage } from "element-plus";
const jsonData = ref({});
// 自动转换 JSON 数据为响应式对象
const fields = ref({});
const options = ref([]);
const editField = ref(null);
const editingValues = reactive({});
const editableInput = ref(null);
const configName = ref();
const onSubmitOption = async (option) => {
  const response = await getConfig(option);
  if (response && response.data) {
    jsonData.value = response.data;
    fields.value = response.data;
  }
};

const handleEdit = async (key) => {
  editField.value = key;
  editingValues[key] = fields.value[key].value;
  const ls_object = { ...fields.value[key] };
  await nextTick(); // 确保 DOM 更新
  // 直接查找 DOM 元素  el-textarea textarea
  const dom_src =
    ls_object.types === "text"
      ? `#edit-input .el-input input`
      : `#edit-input .el-textarea textarea`;
  const inputElement = document.querySelector(dom_src);
  if (inputElement) {
    inputElement.focus();
  }
};

const handleBlur = async (key) => {
  const originalValue = fields.value[key].value;
  const newValue = editingValues[key];

  if (originalValue !== newValue) {
    try {
      await saveChanges(key, newValue);
    } catch (error) {
      console.error("保存失败:", error);
    }
  }

  editField.value = null;
};

const saveChanges = async (key, newValue) => {
  const newobject = {
    ...fields.value[key],
  };
  newobject.value = newValue;
  fields.value[key].value = newobject;
  jsonData.value[key] = newobject;

  const response = await updateConfig(
    String(newValue),
    fields.value[key].name,
    key
  );
  ElMessage({
    message: response.message,
    type: "success",
  });
};
const handleSelectChange = (key, newValue) => {
  saveChanges(key, newValue);
};
const handleSwitchClick = (key, newValue) => {
  saveChanges(key, newValue);
};

const handleClickOutside = (event) => {
  if (editField.value !== null) {
    const inputElement = editableInput.value?.$el;
    if (inputElement && !inputElement.contains(event.target)) {
      handleBlur(editField.value);
    }
  }
};
onMounted(async () => {
  document.addEventListener("click", handleClickOutside);
  const response = await getOption();
  if (response && response.data) {
    options.value = response.data.map((item) => {
      return {
        label: item.script_name,
        value: item.script_name,
      };
    });
  }
});
const handleFocus = () => {
  document.removeEventListener("click", handleClickOutside);
};

onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>
  
  <style lang="scss" scoped>
.config {
  background: #fff;
  margin-top: 20px;
  padding: 16px;
  border-radius: 8px;
}

::deep .el-descriptions__header {
  margin: 16px 0;
  text-align: center;
}

:deep(.el-input) {
  width: 100%;
}
td {
  min-height: 100px;
}
</style>
  
    